package com.lg.rpc.discovery.zookeeper;

import com.lg.rpc.client.ConnectManage;
import com.lg.rpc.common.protocol.util.Constant;
import com.lg.rpc.registry.ServiceDiscovery;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 基于 ZooKeeper 的服务发现接口实现
 *
 * @author by Mr. Li 2020/5/22 0:36
 */
@Slf4j
public class ZookeeperServiceDiscovery implements ServiceDiscovery {
    private final CountDownLatch latch = new CountDownLatch(1);

    private volatile List<String> dataList = new ArrayList<>();

    private String zkAddress;
    private ZooKeeper zookeeper;

    /**
     * 使用  CountDownLatch 增强
     *
     * @param zkAddress
     */
    public ZookeeperServiceDiscovery(String zkAddress) {
        this.zkAddress = zkAddress;
        zookeeper = connectServer();
        if (zookeeper != null) {
            watchNode(zookeeper);
        }
    }

    /**
     * 监控子节点是否 发生改变
     *
     * @param zk
     */
    private void watchNode(ZooKeeper zk) {
        try {
            // 获取所有持久节点
            List<String> addressList = zk.getChildren(Constant.ZK_REGISTRY_PATH, false);

            // 拼接路径
            // 获取 address 节点
            String address;
            int size = addressList.size();
            for (int i = 0; i < size; i++) {
                address = Constant.ZK_REGISTRY_PATH + "/" + addressList.get(i);
                List<String> nodeList = zk.getChildren(address, event -> {
                    if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
                        watchNode(zk);
                    }
                });
                List<String> dataList = new ArrayList<>();
                for (String node : nodeList) {
                    byte[] bytes = zk.getData(address + "/" + node, false, null);
                    dataList.add(new String(bytes));
                }
                log.debug("node data: {}", dataList);
                this.dataList = dataList;

                log.debug("Service discovery triggered updating connected server node.");
                UpdateConnectedServer();
            }
        } catch (KeeperException | InterruptedException e) {
            log.error("", e);
        }
    }

    private void UpdateConnectedServer() {
        ConnectManage.getInstance().updateConnectedServer(this.dataList);
    }

    /**
     * 连接 zk
     *
     * @return
     */
    private ZooKeeper connectServer() {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(zkAddress, Constant.ZK_SESSION_TIMEOUT, event -> {
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    latch.countDown();
                }
            });
            latch.await();
        } catch (IOException | InterruptedException e) {
            log.error("", e);
        }
        return zk;
    }

    @Override
    public String discover(String serviceName) {
        String data = null;
        int size = dataList.size();
        if (size > 0) {
            if (size == 1) {
                data = dataList.get(0);
                log.debug("using only data: {}", data);
            } else {
                data = dataList.get(ThreadLocalRandom.current().nextInt(size));
                log.debug("using random data: {}", data);
            }
        }
        return data;

    }

    @Override
    public void stop() {
        if (zookeeper != null) {
            try {
                zookeeper.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
}
